package com.ww.grtsmanager.exception;

import com.ww.grtsmanager.vo.EduResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;


/**
 * 加上这个注解后就变成了全局异常处理类（器）了
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    //捕获所有的异常，这个项目的任何位置报错了 最终都会来到这里执行代码
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public EduResult defaultErrorHandler(Exception ex, HttpServletResponse response){
        ex.printStackTrace();
        //实际的状态码是200，改成500
        response.setStatus(500);
        //从jsr303异常里面获取message，把message传到页面去就行了
        if (ex instanceof BindException){
            BindException bindException = (BindException) ex;//从父亲强转为儿子
            BindingResult bindingResult = bindException.getBindingResult();
            ObjectError objectError = bindingResult.getAllErrors().get(0);
            String defaultMessage = objectError.getDefaultMessage();
            if (defaultMessage.length()<15)
                return  EduResult.error(defaultMessage);
        }
        //判断是否为我们抛出去的异常
        if (ex instanceof RuntimeException){
            String message = ex.getMessage();
            if (message.length()<15){
                //message:自己抛的"讲师名称不能为空"
                return EduResult.error(message);
            }
        }
        return EduResult.error("系统出错，请联系管理员");
    }
}

